package com.credit.util;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.credit.entity.CreditLoanLog;


public class BeanToMapUtil {
	private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	//string pattern = "(\"([^,^\"]+)\":\"([^:^\"]+)\")|(\"([^,^\"]+)\":([\\d]+))"; //从网上找的有问题
   // private static final String jsonRegex = "^\\{\"(.*?)\":[\\[\"](.*?)[\"\\]]\\}$";
    private static final String jsonRegex = "^\\{((\"(.*?)\":[\\[\"\\{](.*?)[\"\\]\\}l])|(\"(.*?)\":([\\d]+)))\\}$";
    private static final String jsonStrArrayRegex = "^\\[\"?(.*?)\"?\\]$";
    //private static final String jsonObjectArrayRegex = "^\\[\\{?\"(.*?)\"?:?[\\[?\"?](.*?)?[\"?\\]?]\\}\\]$";
    private static final String jsonObjectArrayRegex = "^\\[\\{?(.*?)\\}?\\]$";
    
    /**
     * 实体转成map
     * @param serializable
     * @param paramsMap
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
	public static void toMap(Serializable serializable,Map<String, Object> paramsMap) throws IllegalArgumentException, IllegalAccessException {
		
		Class<?> clazz = serializable.getClass();
		
		//Field[] fields = serializable.getClass().getDeclaredFields();
		for(;clazz!=Object.class;clazz = clazz.getSuperclass()){
			Field[] fields = clazz.getDeclaredFields();
			
			for (int i = 0; i < fields.length; i++) {
				Field field = fields[i];
				field.setAccessible(true);
				
				if(field.get(serializable)==null){
					paramsMap.put(field.getName(), null);
				}else{
					if(field.get(serializable) instanceof String){
						if(field.get(serializable)!=null){
							if(String.valueOf(field.get(serializable)).matches(jsonObjectArrayRegex)){
								List<Map<String,Object>> paramsJsonList = new ArrayList<Map<String,Object>>();
								List<String> paramsStrList = new ArrayList<String>();

								try{
									JSONArray jsonArray = JSONArray.parseArray(String.valueOf(field.get(serializable)));
									for(int j=0;j<jsonArray.size();j++){
										if(jsonArray.get(j) instanceof JSONObject){
											Map<String,Object> jsonMap = new HashMap<String,Object>();
											jsonToMap((JSONObject)jsonArray.get(j),jsonMap);
											paramsJsonList.add(jsonMap);
										}else{
											paramsStrList.add(String.valueOf(jsonArray.get(j)));
										}
									}
									
									if(paramsJsonList.size()>0){
										paramsMap.put(field.getName(), paramsJsonList);
									}else if(paramsStrList.size()>0){
										paramsMap.put(field.getName(), paramsStrList);
									}else{
										paramsMap.put(field.getName(), paramsStrList);
									}
								}catch(JSONException e){
									paramsMap.put(field.getName(), null);
								}
							}else if(String.valueOf(field.get(serializable)).matches(jsonRegex)){
								Map<String,Object> jsonMap = new HashMap<String,Object>();
								jsonToMap(JSONObject.parseObject(String.valueOf(field.get(serializable))),jsonMap);
								paramsMap.put(field.getName(), jsonMap);
							}else{
								paramsMap.put(field.getName(), String.valueOf(field.get(serializable)));
							}
						}else{
							paramsMap.put(field.getName(), String.valueOf(field.get(serializable)));
						}
					}else if(field.get(serializable) instanceof Integer){
						paramsMap.put(field.getName(), field.get(serializable));
					}else if(field.get(serializable) instanceof Date){//时间类型改成时间戳
						paramsMap.put(field.getName(), ((Date)field.get(serializable)).getTime()/*sdf.format(field.get(serializable))*/);
					}else if(field.get(serializable) instanceof BigDecimal){
						paramsMap.put(field.getName(), field.get(serializable));
					}else if(field.get(serializable) instanceof Float){
						paramsMap.put(field.getName(), field.get(serializable));
					}else if(field.get(serializable) instanceof Long){
						paramsMap.put(field.getName(), field.get(serializable));
					}else if(field.get(serializable) instanceof Double){
						paramsMap.put(field.getName(), field.get(serializable));
					}else if(field.get(serializable) instanceof Short){
						paramsMap.put(field.getName(), field.get(serializable));
					}else if(field.get(serializable) instanceof Byte){
						paramsMap.put(field.getName(), field.get(serializable));
					}else if(field.get(serializable) instanceof Boolean){
						paramsMap.put(field.getName(), field.get(serializable));
					}else if(field.get(serializable) instanceof Character){
						paramsMap.put(field.getName(), field.get(serializable));
					}else{
						Map<String, Object> subParamsMap = new HashMap<String, Object>();
						paramsMap.put(field.getName(), subParamsMap);
						toMap(( Serializable)field.get(serializable),subParamsMap);
					}
				}
				
			}
			
		}
		

		
	}

	private static void jsonToMap(JSONObject jsonObject,Map<String,Object> map ) {
		Iterator<String> it = jsonObject.keySet().iterator();
		while(it.hasNext()){
			String key = it.next();
			String value = jsonObject.getString(key);
			
			if(!StringUtils.isEmpty(value)&&value.matches(jsonStrArrayRegex)){
				JSONArray array = JSONArray.parseArray(value);
				List<String> list = new ArrayList<String>();
				for(int i=0;i<array.size();i++){
					list.add(array.getString(i));
				}
				map.put(key, list);
			}else if(!StringUtils.isEmpty(value)&&value.matches(jsonObjectArrayRegex)){
				Map<String,Object> subJsonMap = new HashMap<String,Object>();
				map.put(key, subJsonMap);
				jsonToMap(JSONObject.parseObject(value),subJsonMap);
			}else{
				map.put(key, value);
			}
		}
	}



	public static Map<String, Object> getMap(Serializable serializable) throws IllegalArgumentException, IllegalAccessException {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		toMap(serializable, paramsMap);
		return paramsMap;
	}
	
	



	/**
	 * 剔除无用字段
	 * @param resultMap
	 * @param productUselessFieldList
	 */
	public static void removeUselessField(Map<String, Object> resultMap, List<String> uselessFieldList) {
		for(String field:uselessFieldList){
			resultMap.remove(field);
		}
		
	}
	
	
	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
/*		System.out.println("{\"url\":\"http:\\/\\/test.file.tiplus.cn\\/task\\/6477\\/1478855960845.jpg\",\"width\":864,\"height\":864,\"recodeTime\":\"2016-11-11 17:19:20\"}".matches(jsonRegex));
		String test = "[{\"url\":\"http\",\"a\":\"bb\"},{\"url\":\"http2\",\"a\":\"cc\"}]";
		String test2 = "[\"56\",\"99\"]";
		JSONArray array = JSONArray.fromObject(test);*/
		
		
/*		String str = "[{\"number\":\"1)\",\"body\":\"赤道穿过下列哪个大洲的大部分（ ? ）<table><tbody><tr><td>A．南极洲<\\/td><\\/tr><tr><td>B．南美洲<\\/td><\\/tr><tr><td>C．大洋洲<\\/td><\\/tr><tr><td>D．欧洲<\\/td><\\/tr><\\/tbody><\\/table>\",\"optionCount\":4,\"answer\":\"B\",\"explanation\":\"试题分析：赤道穿过的大陆主要是非洲和南美洲，赤道没有经过南极洲和欧洲，而赤道穿过大洋洲的群岛地区。<br \\/>考点：本题考查世界地理概况。<br \\/>点评：本题难度一般，本题属于无图考图，学生只要掌握世界主要的海陆分布即可。\",\"type\":\"IT002\",\"tags\":[\"世界的陆地和海洋\"]}]";
		System.out.println(str.matches(jsonObjectArrayRegex));
		
		String str2 = "[\"世界的陆地和海洋\",\"世界的陆地和海洋\",\"世界的陆地和海洋\"]";
		System.out.println(str2.matches(jsonStrArrayRegex));*/
		
	/*	
		String str = "[{\"id\":1079,\"title\":\"根目录\",\"isIndex\":false},{\"id\":1123,\"title\":\"第3章 三角恒等变换\",\"isIndex\":false},{\"id\":1125,\"title\":\"地球仪、经纬网极其地理意义\",\"isIndex\":false}]";
		MyTest test = new MyTest();
		test.setCasecade(str);
		System.out.println(JSONArray.fromObject(getMap(test)));*/
		
		
//		String str = "{\"tags\":[爱情]}";
//		JSONArray array = JSONArray.fromObject(str);
		
		
	/*	for (int i = 0; i < array.size(); i++) {
			System.out.println(array.get(i) instanceof JSONObject);
		
		}*/
		String jsonRegex2 = "^\\{\"([^,^\"]+)\":\"([^:^\"]+)\"\\}$";
		String str = "{\"licence\":[65,89],\"annualFlow\":{\"er\":\"g\"},\"address\":\"dfsdf\",\"companyName\":\"天地会\",\"operateYears\":1122,\"userId\":{\"44\":\"df\"}}";
		String str2 = "{\"url\":\"http:\\/\\/test.file.tiplus.cn\\/task\\/6477\\/1478855960845.jpg\",\"width\":864,\"recodeTime\":\"2016-11-11 17:19:20\"}";
		System.out.println(str2.matches(jsonRegex));
		
		
	}

	public static List<Map<String, Object>> getList(List<? extends Serializable> list) throws IllegalArgumentException, IllegalAccessException {
		List<Map<String,Object>> returnList = new ArrayList<Map<String,Object>>();
		for(Serializable serializable:list){
			returnList.add(getMap(serializable));
		}
		return returnList;
	}
	
}
